#include "mainwindow.h"
#include <QApplication>
#include <QCloseEvent>
#include <QTimer>
#include <QMessageBox>
#include <QProcess>
#include <QFile>
#include <QTextStream>
#include <QDir>
#include <QTime>
#include <QMenuBar>
#include <QWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFormLayout>
#include <QSpinBox>
#include <QLineEdit>
#include <QCheckBox>
#include <QPushButton>
#include <QGroupBox>
#include <QLabel>
#include <QStandardPaths>
#include <QScrollArea>
#include <QGridLayout>
#include <QTableWidget>
#include <QHeaderView>
#include <QIcon>
#include <QInputDialog>
#include <QDialog>
#include <QDialogButtonBox>
#include <QDateTime>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , trayIcon(nullptr)
    , trayIconMenu(nullptr)
    , refreshTimer(nullptr)
    , systemInfoTimer(nullptr)
    , systemInfoTable(nullptr)
    , lastReceivedBytes(0)
    , lastTransmittedBytes(0)
    , lastReadSectors(0)
    , lastWriteSectors(0)
{
    setWindowTitle(tr("CPU调度优化工具"));
    setMinimumSize(1000, 700);
    
    // 加载并设置窗口图标
    QIcon appIcon(":/icons/application.png");
    if (appIcon.isNull()) {
        qWarning() << "Failed to load application icon from :/icons/application.png";
    } else {
        setWindowIcon(appIcon);
        qDebug() << "Successfully set window icon";
    }
    
    createActions();
    createMenus();
    createCentralWidget();
    createStatusBar();
    createTrayIcon();
    
    // Initialize last network time
    lastNetworkTime = QDateTime::currentDateTime();
    // Initialize last IO time
    lastIOTime = QDateTime::currentDateTime();
    
    // Setup refresh timer for service status
    refreshTimer = new QTimer(this);
    connect(refreshTimer, &QTimer::timeout, this, &MainWindow::refreshStatus);
    refreshTimer->start(5000); // Refresh every 5 seconds
    
    // Setup timer for system info (1 second as requested)
    systemInfoTimer = new QTimer(this);
    connect(systemInfoTimer, &QTimer::timeout, this, &MainWindow::updateSystemInfo);
    systemInfoTimer->start(1000); // Refresh every 1 second
    
    // Load configuration and update status
    loadSettings();
    updateServiceStatus();
    updateSystemInfo();
    
    // Show main window
    show();
}

MainWindow::~MainWindow()
{
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (trayIcon && trayIcon->isVisible()) {
        hide();
        event->ignore();
    } else {
        event->accept();
    }
}

void MainWindow::saveSettings()
{
    // 保存配置到构建目录下的配置文件
    QString configPath = QDir::currentPath() + "/cpu-scheduler.conf";
    
    QFile file(configPath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(this, tr("错误"), tr("无法写入配置文件: %1").arg(configPath));
        return;
    }
    
    QTextStream out(&file);
    out << "# CPU调度优化配置文件\n";
    out << "# 修改后需要重新安装服务才能生效\n\n";
    
    out << "# 监控设置\n";
    out << QString("CHECK_INTERVAL=%1           # 检查间隔(秒)\n").arg(checkIntervalSpinBox->value());
    out << QString("HIGH_FREQ_THRESHOLD=%1     # 高频率阈值(%%)\n").arg(highFreqThresholdSpinBox->value());
    out << QString("LOW_FREQ_THRESHOLD=%1      # 低频率阈值(%%)\n").arg(lowFreqThresholdSpinBox->value());
    out << QString("SUSTAINED_PERIOD_HIGH=%1   # 高负载持续时间(秒)\n").arg(sustainedPeriodHighSpinBox->value());
    out << QString("SUSTAINED_PERIOD_LOW=%1    # 低负载持续时间(秒)\n\n").arg(sustainedPeriodLowSpinBox->value());
    
    out << "# 频率调整\n";
    out << QString("FREQ_REDUCTION=%1          # 降频幅度(%%)\n").arg(freqReductionSpinBox->value());
    out << QString("FREQ_INCREASE=%1           # 升频幅度(%%)\n").arg(freqIncreaseSpinBox->value());
    out << QString("TARGET_FREQ_AFTER_REDUCTION=%1  # 降频后目标频率(%%)\n\n").arg(targetFreqAfterReductionSpinBox->value());
    
    out << "# IO负载阈值\n";
    out << QString("IO_CRITICAL_THRESHOLD=%1   # 极端IO负载(%%)\n").arg(ioCriticalThresholdSpinBox->value());
    out << QString("IO_SEVERE_THRESHOLD=%1     # 严重IO负载(%%)\n").arg(ioSevereThresholdSpinBox->value());
    out << QString("IO_HIGH_THRESHOLD=%1       # 高IO负载(%%)\n\n").arg(ioHighThresholdSpinBox->value());
    
    file.close();
    
    // 提示用户需要重新安装服务才能使配置生效
    QMessageBox::information(this, tr("设置"), tr("配置已保存到: %1\n需要重新安装服务才能使配置生效").arg(configPath));
}

void MainWindow::loadSettings()
{
    // 从构建目录加载配置
    QString configPath = QDir::currentPath() + "/cpu-scheduler.conf";
    
    QFile file(configPath);
    if (!file.exists()) {
        loadDefaultSettings();
        return;
    }
    
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::warning(this, tr("错误"), tr("无法读取配置文件"));
        loadDefaultSettings();
        return;
    }
    
    QTextStream in(&file);
    QString line;
    while (!in.atEnd()) {
        line = in.readLine().trimmed();
        if (line.startsWith("#") || line.isEmpty()) {
            continue;
        }
        
        QStringList parts = line.split("=");
        if (parts.size() != 2) {
            continue;
        }
        
        QString key = parts[0].trimmed();
        QString value = parts[1].trimmed();
        
        // Remove quotes from value if present
        if (value.startsWith("\"") && value.endsWith("\"")) {
            value = value.mid(1, value.length() - 2);
        }
        
        bool ok;
        int intValue = value.toInt(&ok);
        
        if (key == "CHECK_INTERVAL") {
            checkIntervalSpinBox->setValue(ok ? intValue : 5);
        } else if (key == "HIGH_FREQ_THRESHOLD") {
            highFreqThresholdSpinBox->setValue(ok ? intValue : 80);
        } else if (key == "LOW_FREQ_THRESHOLD") {
            lowFreqThresholdSpinBox->setValue(ok ? intValue : 30);
        } else if (key == "SUSTAINED_PERIOD_HIGH") {
            sustainedPeriodHighSpinBox->setValue(ok ? intValue : 10);
        } else if (key == "SUSTAINED_PERIOD_LOW") {
            sustainedPeriodLowSpinBox->setValue(ok ? intValue : 60);
        } else if (key == "FREQ_REDUCTION") {
            freqReductionSpinBox->setValue(ok ? intValue : 25);
        } else if (key == "FREQ_INCREASE") {
            freqIncreaseSpinBox->setValue(ok ? intValue : 25);
        } else if (key == "TARGET_FREQ_AFTER_REDUCTION") {
            targetFreqAfterReductionSpinBox->setValue(ok ? intValue : 75);
        } else if (key == "IO_CRITICAL_THRESHOLD") {
            ioCriticalThresholdSpinBox->setValue(ok ? intValue : 90);
        } else if (key == "IO_SEVERE_THRESHOLD") {
            ioSevereThresholdSpinBox->setValue(ok ? intValue : 80);
        } else if (key == "IO_HIGH_THRESHOLD") {
            ioHighThresholdSpinBox->setValue(ok ? intValue : 70);
        }
    }
    
    file.close();
}

void MainWindow::loadDefaultSettings()
{
    checkIntervalSpinBox->setValue(5);
    highFreqThresholdSpinBox->setValue(80);
    lowFreqThresholdSpinBox->setValue(30);
    sustainedPeriodHighSpinBox->setValue(10);
    sustainedPeriodLowSpinBox->setValue(60);
    freqReductionSpinBox->setValue(25);
    freqIncreaseSpinBox->setValue(25);
    targetFreqAfterReductionSpinBox->setValue(75);
    ioCriticalThresholdSpinBox->setValue(90);
    ioSevereThresholdSpinBox->setValue(80);
    ioHighThresholdSpinBox->setValue(70);
}

void MainWindow::restoreDefaultSettings()
{
    int ret = QMessageBox::question(this, tr("恢复默认设置"), 
                                  tr("确定要恢复所有设置为默认值吗？"),
                                  QMessageBox::Yes | QMessageBox::No);
    
    if (ret == QMessageBox::Yes) {
        loadDefaultSettings();
        saveSettings();
    }
}

void MainWindow::startService()
{
    // 先执行安装服务操作，确保使用最新的配置
    installService();
    
    // 然后启动服务
    // Use pkexec or gksudo for GUI authentication
    QString command;
    QStringList args;
    
    // Try pkexec first (preferred method)
    if (QStandardPaths::findExecutable("pkexec") != QString()) {
        command = "pkexec";
        args << "systemctl" << "start" << "cpu-scheduler.service";
    } 
    // Fallback to gksudo if pkexec is not available
    else if (QStandardPaths::findExecutable("gksudo") != QString()) {
        command = "gksudo";
        args << "systemctl start cpu-scheduler.service";
    } 
    // Fallback to kdesudo if using KDE
    else if (QStandardPaths::findExecutable("kdesudo") != QString()) {
        command = "kdesudo";
        args << "systemctl start cpu-scheduler.service";
    } 
    // If none of the GUI sudo tools are available, show an error
    else {
        QMessageBox::warning(this, tr("权限不足"), 
                             tr("未找到图形界面的权限提升工具 (如 pkexec, gksudo, kdesudo)。\n"
                                "请确保已安装这些工具之一，或在终端中手动运行:\n"
                                "sudo systemctl start cpu-scheduler.service"));
        return;
    }
    
    QProcess *process = new QProcess(this);
    process->start(command, args);
    
    // Wait for the process to finish
    if (!process->waitForFinished(30000)) { // Wait up to 30 seconds
        QMessageBox::warning(this, tr("服务控制"), tr("操作超时"));
        process->kill();
        process->waitForFinished(1000);
    } else if (process->exitCode() == 0) {
        QMessageBox::information(this, tr("服务控制"), tr("服务启动成功"));
    } else {
        QString errorOutput = process->readAllStandardError();
        QMessageBox::warning(this, tr("服务控制"), 
                             tr("服务启动失败: %1").arg(errorOutput));
    }
    
    process->deleteLater();
    updateServiceStatus();
}

void MainWindow::stopService()
{
    // Use pkexec or gksudo for GUI authentication
    QString command;
    QStringList args;
    
    // Try pkexec first (preferred method)
    if (QStandardPaths::findExecutable("pkexec") != QString()) {
        command = "pkexec";
        args << "systemctl" << "stop" << "cpu-scheduler.service";
    } 
    // Fallback to gksudo if pkexec is not available
    else if (QStandardPaths::findExecutable("gksudo") != QString()) {
        command = "gksudo";
        args << "systemctl stop cpu-scheduler.service";
    } 
    // Fallback to kdesudo if using KDE
    else if (QStandardPaths::findExecutable("kdesudo") != QString()) {
        command = "kdesudo";
        args << "systemctl stop cpu-scheduler.service";
    } 
    // If none of the GUI sudo tools are available, show an error
    else {
        QMessageBox::warning(this, tr("权限不足"), 
                             tr("未找到图形界面的权限提升工具 (如 pkexec, gksudo, kdesudo)。\n"
                                "请确保已安装这些工具之一，或在终端中手动运行:\n"
                                "sudo systemctl stop cpu-scheduler.service"));
        return;
    }
    
    QProcess *process = new QProcess(this);
    process->start(command, args);
    
    // Wait for the process to finish
    if (!process->waitForFinished(30000)) { // Wait up to 30 seconds
        QMessageBox::warning(this, tr("服务控制"), tr("操作超时"));
        process->kill();
        process->waitForFinished(1000);
    } else if (process->exitCode() == 0) {
        QMessageBox::information(this, tr("服务控制"), tr("服务停止成功"));
    } else {
        QString errorOutput = process->readAllStandardError();
        QMessageBox::warning(this, tr("服务控制"), 
                             tr("服务停止失败: %1").arg(errorOutput));
    }
    
    process->deleteLater();
    updateServiceStatus();
}

void MainWindow::restartService()
{
    // Use pkexec or gksudo for GUI authentication
    QString command;
    QStringList args;
    
    // Try pkexec first (preferred method)
    if (QStandardPaths::findExecutable("pkexec") != QString()) {
        command = "pkexec";
        args << "systemctl" << "restart" << "cpu-scheduler.service";
    } 
    // Fallback to gksudo if pkexec is not available
    else if (QStandardPaths::findExecutable("gksudo") != QString()) {
        command = "gksudo";
        args << "systemctl restart cpu-scheduler.service";
    } 
    // Fallback to kdesudo if using KDE
    else if (QStandardPaths::findExecutable("kdesudo") != QString()) {
        command = "kdesudo";
        args << "systemctl restart cpu-scheduler.service";
    } 
    // If none of the GUI sudo tools are available, show an error
    else {
        QMessageBox::warning(this, tr("权限不足"), 
                             tr("未找到图形界面的权限提升工具 (如 pkexec, gksudo, kdesudo)。\n"
                                "请确保已安装这些工具之一，或在终端中手动运行:\n"
                                "sudo systemctl restart cpu-scheduler.service"));
        return;
    }
    
    QProcess *process = new QProcess(this);
    process->start(command, args);
    
    // Wait for the process to finish
    if (!process->waitForFinished(30000)) { // Wait up to 30 seconds
        QMessageBox::warning(this, tr("服务控制"), tr("操作超时"));
        process->kill();
        process->waitForFinished(1000);
    } else if (process->exitCode() == 0) {
        QMessageBox::information(this, tr("服务控制"), tr("服务重启成功"));
    } else {
        QString errorOutput = process->readAllStandardError();
        QMessageBox::warning(this, tr("服务控制"), 
                             tr("服务重启失败: %1").arg(errorOutput));
    }
    
    process->deleteLater();
    updateServiceStatus();
}

void MainWindow::checkStatus()
{
    updateServiceStatus();
    // QMessageBox::information(this, tr("服务状态"), serviceStatusLabel->text());
    // 由于移除了serviceStatusLabel，我们直接从系统获取状态
    QProcess process;
    process.start("systemctl", QStringList() << "is-active" << "cpu-scheduler.service");
    process.waitForFinished();
    
    QString status = process.readAllStandardOutput().trimmed();
    QString statusText;
    if (status == "active") {
        statusText = tr("运行中");
    } else if (status == "inactive") {
        statusText = tr("已停止");
    } else {
        statusText = tr("未知");
    }
    
    QMessageBox::information(this, tr("服务状态"), statusText);
}

void MainWindow::showAbout()
{
    QMessageBox::about(this, tr("关于CPU调度优化工具"),
                       tr("<h3>CPU调度优化工具 1.0</h3>"
                          "<p>这是一个用于动态调整CPU频率的图形界面工具</p>"
                          "<p>通过监控系统负载，在持续高负载时自动降低CPU频率上限，"
                          "以减少功耗和热量产生，提高系统稳定性。</p>"));
}

void MainWindow::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason) {
    case QSystemTrayIcon::Trigger:
    case QSystemTrayIcon::DoubleClick:
        showNormal();
        activateWindow();
        break;
    default:
        break;
    }
}

void MainWindow::refreshStatus()
{
    updateServiceStatus();
}

void MainWindow::updateSystemInfo()
{
    // Clear previous data
    systemInfoTable->setRowCount(0);
    
    // Get CPU info
    QProcess cpuProcess;
    cpuProcess.start("uptime");
    cpuProcess.waitForFinished();
    QString cpuInfo = cpuProcess.readAllStandardOutput().trimmed();
    
    // Parse uptime output for better CPU load display
    QString cpuDisplayInfo;
    QString cpuInfoForTooltip;
    
    // Extract load averages from uptime output
    // Format: "HH:MM:SS up X days, HH:MM,  X users,  load average: a.b, c.d, e.f"
    QRegExp loadRegex("load average:\\s*([\\d\\.]+),\\s*([\\d\\.]+),\\s*([\\d\\.]+)");
    if (loadRegex.indexIn(cpuInfo) != -1) {
        QString load1min = loadRegex.cap(1);
        QString load5min = loadRegex.cap(2);
        QString load15min = loadRegex.cap(3);
        
        // Convert to double for percentage calculation (assuming dual-core system)
        double load1 = load1min.toDouble();
        double load5 = load5min.toDouble();
        double load15 = load15min.toDouble();
        
        // Get CPU count for better percentage calculation
        QProcess cpuCountProcess;
        cpuCountProcess.start("nproc");
        cpuCountProcess.waitForFinished();
        int cpuCount = QString(cpuCountProcess.readAllStandardOutput().trimmed()).toInt();
        if (cpuCount == 0) cpuCount = 1; // Fallback
        
        // Calculate load percentage
        double loadPercent1 = (load1 / cpuCount) * 100.0;
        double loadPercent5 = (load5 / cpuCount) * 100.0;
        double loadPercent15 = (load15 / cpuCount) * 100.0;
        
        // Create friendly display with status indicators
        QString status;
        QString color;
        if (loadPercent1 > 80) {
            status = "🔴 高负载";
            color = "red";
        } else if (loadPercent1 > 50) {
            status = "🟡 中负载";
            color = "orange";
        } else {
            status = "🟢 低负载";
            color = "green";
        }
        
        cpuDisplayInfo = QString("%1 (%2%) | 5分: %3% | 15分: %4%")
                          .arg(status)
                          .arg(loadPercent1, 0, 'f', 1)
                          .arg(loadPercent5, 0, 'f', 1)
                          .arg(loadPercent15, 0, 'f', 1);
        
        cpuInfoForTooltip = QString("1分: %1 (%2%) | 5分: %3 (%4%) | 15分: %5 (%6%)")
                                .arg(load1min).arg(loadPercent1, 0, 'f', 1)
                                .arg(load5min).arg(loadPercent5, 0, 'f', 1)
                                .arg(load15min).arg(loadPercent15, 0, 'f', 1);
    } else {
        // Fallback to original format if parsing fails
        cpuDisplayInfo = cpuInfo;
        cpuInfoForTooltip = cpuInfo;
        int colonIndex = cpuInfo.lastIndexOf(':');
        if (colonIndex != -1) {
            cpuInfoForTooltip = cpuInfo.mid(colonIndex + 1).trimmed();
        }
    }
    
    // Add CPU info row with enhanced display
    int row = systemInfoTable->rowCount();
    systemInfoTable->insertRow(row);
    systemInfoTable->setItem(row, 0, new QTableWidgetItem(tr("CPU负载")));
    systemInfoTable->setItem(row, 1, new QTableWidgetItem(cpuDisplayInfo));
    
    // Get memory info
    QProcess memProcess;
    memProcess.start("free", QStringList() << "-h");
    memProcess.waitForFinished();
    QString memOutput = memProcess.readAllStandardOutput();
    QStringList memLines = memOutput.split("\n");
    QString memInfo; // Declare memInfo here to use in tooltip
    QString memInfoForTooltip; // Simplified memory info for tooltip
    if (memLines.size() > 1) {
        QStringList memFields = memLines[1].simplified().split(" ");
        if (memFields.size() >= 7) {
            QString totalMem = memFields[1];
            QString usedMem = memFields[2];
            memInfo = QString("%1 / %2").arg(usedMem).arg(totalMem);
            memInfoForTooltip = QString("%1/%2").arg(usedMem).arg(totalMem);
            
            row = systemInfoTable->rowCount();
            systemInfoTable->insertRow(row);
            systemInfoTable->setItem(row, 0, new QTableWidgetItem(tr("内存")));
            systemInfoTable->setItem(row, 1, new QTableWidgetItem(memInfo));
        }
    }
    
    // IO info variables
    QString ioInfoForTooltip; // Simplified IO info for tooltip
    
    // Get IO info using /proc/diskstats for real-time data calculation
    // 通过读取/proc/diskstats获取累计读写扇区数，并计算实时速度
    QFile diskStatsFile("/proc/diskstats");
    if (diskStatsFile.open(QIODevice::ReadOnly)) {
        QTextStream in(&diskStatsFile);
        QString content = in.readAll();
        diskStatsFile.close();
        
        QStringList lines = content.split("\n");
        quint64 currentReadSectors = 0;
        quint64 currentWriteSectors = 0;
        
        // 解析/proc/diskstats中的数据
        // 字段格式: 主设备号 次设备号 设备名 读请求数 读合并数 读扇区数 读等待时间 写请求数 写合并数 写扇区数 写等待时间 IO等待时间 IO等待队列 IO处理时间
        for (const QString& line : lines) {
            QStringList fields = line.simplified().split(" ", Qt::SkipEmptyParts);
            if (fields.size() >= 14) {
                // 只处理物理磁盘设备，忽略loop等虚拟设备
                QString deviceName = fields[2];
                if (!deviceName.startsWith("loop") && !deviceName.startsWith("ram")) {
                    bool ok1, ok2;
                    quint64 readSectors = fields[5].toULongLong(&ok1);   // 读扇区数是第6列（索引5）
                    quint64 writeSectors = fields[9].toULongLong(&ok2);  // 写扇区数是第10列（索引9）
                    
                    if (ok1 && ok2) {
                        currentReadSectors += readSectors;
                        currentWriteSectors += writeSectors;
                    }
                }
            }
        }
        
        // 计算实时IO速度
        QDateTime currentTime = QDateTime::currentDateTime();
        qint64 timeDiff = lastIOTime.msecsTo(currentTime);
        
        double readSpeed = 0.0;
        double writeSpeed = 0.0;
        QString readUnit = "B/s";
        QString writeUnit = "B/s";
        
        if (timeDiff > 0) {
            // 计算扇区数的变化量（每扇区512字节）
            quint64 readSectorsDiff = currentReadSectors - lastReadSectors;
            quint64 writeSectorsDiff = currentWriteSectors - lastWriteSectors;
            
            // 转换为字节并计算每秒速度
            readSpeed = (double)(readSectorsDiff * 512) * 1000.0 / (double)timeDiff;
            writeSpeed = (double)(writeSectorsDiff * 512) * 1000.0 / (double)timeDiff;
            
            // 转换为合适的单位
            if (readSpeed >= 1024.0) {
                readSpeed /= 1024.0;
                readUnit = "KB/s";
            }
            if (readSpeed >= 1024.0 * 1024.0) {
                readSpeed /= (1024.0 * 1024.0);
                readUnit = "MB/s";
            }
            if (readSpeed >= 1024.0 * 1024.0 * 1024.0) {
                readSpeed /= (1024.0 * 1024.0 * 1024.0);
                readUnit = "GB/s";
            }
            
            if (writeSpeed >= 1024.0) {
                writeSpeed /= 1024.0;
                writeUnit = "KB/s";
            }
            if (writeSpeed >= 1024.0 * 1024.0) {
                writeSpeed /= (1024.0 * 1024.0);
                writeUnit = "MB/s";
            }
            if (writeSpeed >= 1024.0 * 1024.0 * 1024.0) {
                writeSpeed /= (1024.0 * 1024.0 * 1024.0);
                writeUnit = "GB/s";
            }
        }
        
        // 更新界面显示
        QString ioInfo = QString("读取: %1 %2 写入: %3 %4")
                            .arg(readSpeed, 0, 'f', 2)
                            .arg(readUnit)
                            .arg(writeSpeed, 0, 'f', 2)
                            .arg(writeUnit);
        
        ioInfoForTooltip = QString("%1%2/%3%4")
                              .arg(readSpeed, 0, 'f', 0)
                              .arg(readUnit)
                              .arg(writeSpeed, 0, 'f', 0)
                              .arg(writeUnit);
        
        row = systemInfoTable->rowCount();
        systemInfoTable->insertRow(row);
        systemInfoTable->setItem(row, 0, new QTableWidgetItem(tr("磁盘IO")));
        systemInfoTable->setItem(row, 1, new QTableWidgetItem(ioInfo));
        
        // 更新累计值用于下次计算
        lastReadSectors = currentReadSectors;
        lastWriteSectors = currentWriteSectors;
        lastIOTime = currentTime;
    }
    
    // Get network speed
    QProcess netProcess;
    netProcess.start("cat", QStringList() << "/proc/net/dev");
    netProcess.waitForFinished();
    QString netOutput = netProcess.readAllStandardOutput();
    QStringList netLines = netOutput.split("\n");
    
    quint64 currentReceived = 0;
    quint64 currentTransmitted = 0;
    
    // Skip first 2 lines (headers)
    for (int i = 2; i < netLines.size(); ++i) {
        QString line = netLines[i].trimmed();
        if (line.isEmpty()) continue;
        
        // Remove interface name part before ':'
        int colonIndex = line.indexOf(':');
        if (colonIndex != -1) {
            line = line.mid(colonIndex + 1).trimmed();
        }
        
        QStringList fields = line.split(" ", Qt::SkipEmptyParts);
        if (fields.size() >= 9) {
            bool ok1, ok2;
            quint64 received = fields[0].toULongLong(&ok1);
            quint64 transmitted = fields[8].toULongLong(&ok2);
            
            if (ok1 && ok2) {
                currentReceived += received;
                currentTransmitted += transmitted;
            }
        }
    }
    
    QString netInfo; // Declare netInfo here to use in tooltip
    QString netInfoForTooltip; // Simplified network info for tooltip
    // Calculate network speed
    QDateTime currentNetworkTime = QDateTime::currentDateTime();
    qint64 timeDiff = lastNetworkTime.msecsTo(currentNetworkTime);
    
    if (timeDiff > 0) {
        double receivedSpeed = (currentReceived - lastReceivedBytes) * 1000.0 / timeDiff; // bytes per second
        double transmittedSpeed = (currentTransmitted - lastTransmittedBytes) * 1000.0 / timeDiff; // bytes per second
        
        // Convert to appropriate units
        QString receivedStr, transmittedStr;
        QString receivedUnit, transmittedUnit;
        
        if (receivedSpeed < 1024.0) {
            receivedStr = QString::number(receivedSpeed, 'f', 0);
            receivedUnit = "B/s";
        } else if (receivedSpeed < 1024.0 * 1024.0) {
            receivedSpeed /= 1024.0;
            receivedStr = QString::number(receivedSpeed, 'f', 2);
            receivedUnit = "KB/s";
        } else if (receivedSpeed < 1024.0 * 1024.0 * 1024.0) {
            receivedSpeed /= (1024.0 * 1024.0);
            receivedStr = QString::number(receivedSpeed, 'f', 2);
            receivedUnit = "MB/s";
        } else {
            receivedSpeed /= (1024.0 * 1024.0 * 1024.0);
            receivedStr = QString::number(receivedSpeed, 'f', 2);
            receivedUnit = "GB/s";
        }
        
        if (transmittedSpeed < 1024.0) {
            transmittedStr = QString::number(transmittedSpeed, 'f', 0);
            transmittedUnit = "B/s";
        } else if (transmittedSpeed < 1024.0 * 1024.0) {
            transmittedSpeed /= 1024.0;
            transmittedStr = QString::number(transmittedSpeed, 'f', 2);
            transmittedUnit = "KB/s";
        } else if (transmittedSpeed < 1024.0 * 1024.0 * 1024.0) {
            transmittedSpeed /= (1024.0 * 1024.0);
            transmittedStr = QString::number(transmittedSpeed, 'f', 2);
            transmittedUnit = "MB/s";
        } else {
            transmittedSpeed /= (1024.0 * 1024.0 * 1024.0);
            transmittedStr = QString::number(transmittedSpeed, 'f', 2);
            transmittedUnit = "GB/s";
        }
        
        netInfo = QString("↓ %1 %2 ↑ %3 %4")
                     .arg(receivedStr)
                     .arg(receivedUnit)
                     .arg(transmittedStr)
                     .arg(transmittedUnit);
        netInfoForTooltip = QString("↓%1%2 ↑%3%4")
                               .arg(receivedStr)
                               .arg(receivedUnit)
                               .arg(transmittedStr)
                               .arg(transmittedUnit);
        
        row = systemInfoTable->rowCount();
        systemInfoTable->insertRow(row);
        systemInfoTable->setItem(row, 0, new QTableWidgetItem(tr("网络")));
        systemInfoTable->setItem(row, 1, new QTableWidgetItem(netInfo));
    }
    
    // Update tray icon tooltip
    QString tooltip = QString("CPU调度优化工具\nCPU : %1\n内存: %2\nIO  : %3\n网络: %4")
                         .arg(cpuInfoForTooltip)
                         .arg(memInfoForTooltip)
                         .arg(ioInfoForTooltip)
                         .arg(netInfoForTooltip);
    trayIcon->setToolTip(tooltip);
    
    // Update last values for next calculation
    lastReceivedBytes = currentReceived;
    lastTransmittedBytes = currentTransmitted;
    lastNetworkTime = currentNetworkTime;
    
    statusLabel->setText(tr("最后更新: %1").arg(QTime::currentTime().toString("hh:mm:ss")));
}

void MainWindow::showSettingsDialog()
{
    QDialog settingsDialog(this);
    settingsDialog.setWindowTitle(tr("设置"));
    settingsDialog.setModal(true);
    settingsDialog.resize(500, 300);
    
    QVBoxLayout *layout = new QVBoxLayout(&settingsDialog);
    
    // Log settings
    QGroupBox *logGroup = new QGroupBox(tr("日志设置"));
    QFormLayout *logLayout = new QFormLayout;
    
    QLineEdit *logFileLineEdit = new QLineEdit;
    logFileLineEdit->setText("/var/log/cpu-scheduler.log");
    
    QSpinBox *maxLogSizeMBSpinBox = new QSpinBox;
    maxLogSizeMBSpinBox->setRange(1, 100);
    maxLogSizeMBSpinBox->setValue(5);
    maxLogSizeMBSpinBox->setSuffix(tr(" MB"));
    
    QSpinBox *maxLogFilesSpinBox = new QSpinBox;
    maxLogFilesSpinBox->setRange(1, 20);
    maxLogFilesSpinBox->setValue(5);
    
    logLayout->addRow(tr("日志文件:"), logFileLineEdit);
    logLayout->addRow(tr("最大日志大小:"), maxLogSizeMBSpinBox);
    logLayout->addRow(tr("保留日志文件数:"), maxLogFilesSpinBox);
    
    logGroup->setLayout(logLayout);
    
    // Config file settings
    QGroupBox *configGroup = new QGroupBox(tr("配置文件"));
    QFormLayout *configLayout = new QFormLayout;
    
    QLineEdit *configFileLineEdit = new QLineEdit;
    configFileLineEdit->setText("/opt/ohmylinux/cpu-scheduler/cpu-scheduler.conf");
    configFileLineEdit->setReadOnly(true);
    
    QCheckBox *autostartCheckBox = new QCheckBox(tr("开机自动启动"));
    
    // Check if service is set to autostart
    QProcess process;
    process.start("systemctl", QStringList() << "is-enabled" << "cpu-scheduler.service");
    process.waitForFinished();
    QString output = process.readAllStandardOutput().trimmed();
    autostartCheckBox->setChecked(output == "enabled");
    
    configLayout->addRow(tr("配置文件位置:"), configFileLineEdit);
    configLayout->addRow(tr("服务设置:"), autostartCheckBox);
    
    configGroup->setLayout(configLayout);
    
    layout->addWidget(logGroup);
    layout->addWidget(configGroup);
    
    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    layout->addWidget(buttonBox);
    
    connect(buttonBox, &QDialogButtonBox::accepted, &settingsDialog, &QDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, &settingsDialog, &QDialog::reject);
    
    settingsDialog.exec();
}

void MainWindow::createActions()
{
    startAct = new QAction(tr("启动服务(&T)"), this);
    startAct->setStatusTip(tr("启动CPU调度服务"));
    connect(startAct, &QAction::triggered, this, &MainWindow::startService);

    stopAct = new QAction(tr("停止服务(&P)"), this);
    stopAct->setStatusTip(tr("停止CPU调度服务"));
    connect(stopAct, &QAction::triggered, this, &MainWindow::stopService);

    restartAct = new QAction(tr("重启服务(&R)"), this);
    restartAct->setStatusTip(tr("重启CPU调度服务"));
    connect(restartAct, &QAction::triggered, this, &MainWindow::restartService);

    statusAct = new QAction(tr("检查状态(&C)"), this);
    statusAct->setStatusTip(tr("检查服务运行状态"));
    connect(statusAct, &QAction::triggered, this, &MainWindow::checkStatus);

    quitAct = new QAction(tr("退出(&Q)"), this);
    quitAct->setStatusTip(tr("退出应用程序"));
    connect(quitAct, &QAction::triggered, qApp, &QApplication::quit);
    
    showMainAct = new QAction(tr("显示主界面(&M)"), this);
    showMainAct->setStatusTip(tr("显示主界面"));
    connect(showMainAct, &QAction::triggered, [this]() {
        showNormal();
        activateWindow();
    });

    aboutAct = new QAction(tr("关于(&A)"), this);
    aboutAct->setStatusTip(tr("显示程序信息"));
    connect(aboutAct, &QAction::triggered, this, &MainWindow::showAbout);

    aboutQtAct = new QAction(tr("关于Qt(&Q)"), this);
    aboutQtAct->setStatusTip(tr("显示Qt库信息"));
    connect(aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt);
    
    settingsAct = new QAction(tr("设置(&S)"), this);
    settingsAct->setStatusTip(tr("显示设置"));
    connect(settingsAct, &QAction::triggered, this, &MainWindow::showSettingsDialog);
    
    installAct = new QAction(tr("安装服务(&I)"), this);
    installAct->setStatusTip(tr("安装CPU调度服务到系统"));
    connect(installAct, &QAction::triggered, this, &MainWindow::installService);
    
    uninstallAct = new QAction(tr("卸载服务(&U)"), this);
    uninstallAct->setStatusTip(tr("从系统中卸载CPU调度服务"));
    connect(uninstallAct, &QAction::triggered, this, &MainWindow::uninstallService);
}

void MainWindow::createMenus()
{
    fileMenu = menuBar()->addMenu(tr("文件(&F)"));
    fileMenu->addAction(settingsAct);
    fileMenu->addSeparator();
    fileMenu->addAction(quitAct);

    serviceMenu = menuBar()->addMenu(tr("服务(&V)"));
    serviceMenu->addAction(installAct);
    serviceMenu->addAction(uninstallAct);
    serviceMenu->addSeparator();
    serviceMenu->addAction(startAct);
    serviceMenu->addAction(stopAct);
    serviceMenu->addAction(restartAct);
    serviceMenu->addSeparator();
    serviceMenu->addAction(statusAct);

    helpMenu = menuBar()->addMenu(tr("帮助(&H)"));
    helpMenu->addAction(aboutAct);
    helpMenu->addAction(aboutQtAct);
}

void MainWindow::createCentralWidget()
{
    QWidget *centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);
    
    QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);
    
    // Create a scroll area for settings
    QScrollArea *scrollArea = new QScrollArea;
    scrollArea->setWidgetResizable(true);
    QWidget *scrollWidget = new QWidget;
    scrollArea->setWidget(scrollWidget);
    
    QVBoxLayout *scrollLayout = new QVBoxLayout(scrollWidget);
    
    // First row: Monitoring settings + System info table
    QHBoxLayout *firstRowLayout = new QHBoxLayout;
    
    // Group box for monitoring settings and service status
    QGroupBox *monitoringGroupBox = new QGroupBox(tr("监控设置与服务状态"));
    QVBoxLayout *monitoringGroupLayout = new QVBoxLayout;
    
    // Monitoring settings
    QGroupBox *monitoringGroup = new QGroupBox();
    QFormLayout *monitoringLayout = new QFormLayout;
    
    checkIntervalSpinBox = new QSpinBox;
    checkIntervalSpinBox->setRange(1, 300);
    checkIntervalSpinBox->setSuffix(tr(" 秒"));
    monitoringLayout->addRow(tr("检查间隔:"), checkIntervalSpinBox);
    
    highFreqThresholdSpinBox = new QSpinBox;
    highFreqThresholdSpinBox->setRange(1, 100);
    highFreqThresholdSpinBox->setSuffix(tr(" %"));
    monitoringLayout->addRow(tr("高频率阈值:"), highFreqThresholdSpinBox);
    
    lowFreqThresholdSpinBox = new QSpinBox;
    lowFreqThresholdSpinBox->setRange(1, 100);
    lowFreqThresholdSpinBox->setSuffix(tr(" %"));
    monitoringLayout->addRow(tr("低频率阈值:"), lowFreqThresholdSpinBox);
    
    sustainedPeriodHighSpinBox = new QSpinBox;
    sustainedPeriodHighSpinBox->setRange(1, 300);
    sustainedPeriodHighSpinBox->setSuffix(tr(" 秒"));
    monitoringLayout->addRow(tr("高负载持续时间:"), sustainedPeriodHighSpinBox);
    
    sustainedPeriodLowSpinBox = new QSpinBox;
    sustainedPeriodLowSpinBox->setRange(1, 600);
    sustainedPeriodLowSpinBox->setSuffix(tr(" 秒"));
    monitoringLayout->addRow(tr("低负载持续时间:"), sustainedPeriodLowSpinBox);
    
    monitoringGroup->setLayout(monitoringLayout);
    
    // Service status display (as a single line)
    /*
    QHBoxLayout *serviceStatusLayout = new QHBoxLayout;
    QLabel *serviceStatusTitleLabel = new QLabel(tr("服务状态:"));
    serviceStatusLabel = new QLabel(tr("未知"));
    serviceStatusLayout->addWidget(serviceStatusTitleLabel);
    serviceStatusLayout->addWidget(serviceStatusLabel);
    serviceStatusLayout->addStretch();
    */
    
    monitoringGroupLayout->addWidget(monitoringGroup);
    // monitoringGroupLayout->addLayout(serviceStatusLayout); // 注释掉这一行
    monitoringGroupBox->setLayout(monitoringGroupLayout);
    
    // System info table (Right side)
    QGroupBox *systemInfoGroup = new QGroupBox(tr("系统监控"));
    QVBoxLayout *systemInfoLayout = new QVBoxLayout;
    
    systemInfoTable = new QTableWidget(0, 2);
    systemInfoTable->setHorizontalHeaderLabels(QStringList() << tr("项目") << tr("值"));
    systemInfoTable->horizontalHeader()->setStretchLastSection(true);
    systemInfoTable->verticalHeader()->setVisible(false);
    systemInfoTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    
    systemInfoLayout->addWidget(systemInfoTable);
    systemInfoGroup->setLayout(systemInfoLayout);
    
    firstRowLayout->addWidget(monitoringGroupBox, 1);
    firstRowLayout->addWidget(systemInfoGroup, 1);
    
    // Second row: Other settings groups
    QHBoxLayout *secondRowLayout = new QHBoxLayout;
    
    // Frequency adjustment settings group
    QGroupBox *freqGroup = new QGroupBox(tr("频率调整"));
    QFormLayout *freqLayout = new QFormLayout;
    
    freqReductionSpinBox = new QSpinBox;
    freqReductionSpinBox->setRange(1, 100);
    freqReductionSpinBox->setSuffix(tr(" %"));
    freqLayout->addRow(tr("降频幅度:"), freqReductionSpinBox);
    
    freqIncreaseSpinBox = new QSpinBox;
    freqIncreaseSpinBox->setRange(1, 100);
    freqIncreaseSpinBox->setSuffix(tr(" %"));
    freqLayout->addRow(tr("升频幅度:"), freqIncreaseSpinBox);
    
    targetFreqAfterReductionSpinBox = new QSpinBox;
    targetFreqAfterReductionSpinBox->setRange(10, 100);
    targetFreqAfterReductionSpinBox->setSuffix(tr(" %"));
    freqLayout->addRow(tr("降频后目标频率:"), targetFreqAfterReductionSpinBox);
    
    freqGroup->setLayout(freqLayout);
    
    // IO load threshold settings group
    QGroupBox *ioGroup = new QGroupBox(tr("IO负载阈值"));
    QFormLayout *ioLayout = new QFormLayout;
    
    ioCriticalThresholdSpinBox = new QSpinBox;
    ioCriticalThresholdSpinBox->setRange(1, 100);
    ioCriticalThresholdSpinBox->setSuffix(tr(" %"));
    ioLayout->addRow(tr("极端IO负载阈值:"), ioCriticalThresholdSpinBox);
    
    ioSevereThresholdSpinBox = new QSpinBox;
    ioSevereThresholdSpinBox->setRange(1, 100);
    ioSevereThresholdSpinBox->setSuffix(tr(" %"));
    ioLayout->addRow(tr("严重IO负载阈值:"), ioSevereThresholdSpinBox);
    
    ioHighThresholdSpinBox = new QSpinBox;
    ioHighThresholdSpinBox->setRange(1, 100);
    ioHighThresholdSpinBox->setSuffix(tr(" %"));
    ioLayout->addRow(tr("高IO负载阈值:"), ioHighThresholdSpinBox);
    
    ioGroup->setLayout(ioLayout);
    
    secondRowLayout->addWidget(freqGroup);
    secondRowLayout->addWidget(ioGroup);
    
    // Add layouts to scroll area
    scrollLayout->addLayout(firstRowLayout);
    scrollLayout->addLayout(secondRowLayout);
    
    // Add scroll area to main layout
    mainLayout->addWidget(scrollArea);
    
    // Buttons layout
    QHBoxLayout *buttonsLayout = new QHBoxLayout;
    
    saveButton = new QPushButton(tr("保存设置"));
    connect(saveButton, &QPushButton::clicked, this, &MainWindow::saveSettings);
    
    restoreDefaultButton = new QPushButton(tr("恢复默认设置"));
    connect(restoreDefaultButton, &QPushButton::clicked, this, &MainWindow::restoreDefaultSettings);
    
    installServiceButton = new QPushButton(tr("安装服务"));
    connect(installServiceButton, &QPushButton::clicked, this, &MainWindow::installService);
    
    uninstallServiceButton = new QPushButton(tr("卸载服务"));
    connect(uninstallServiceButton, &QPushButton::clicked, this, &MainWindow::uninstallService);
    
    buttonsLayout->addWidget(saveButton);
    buttonsLayout->addWidget(restoreDefaultButton);
    buttonsLayout->addWidget(installServiceButton);
    buttonsLayout->addWidget(uninstallServiceButton);
    buttonsLayout->addStretch();
    
    // Create service control buttons
    startServiceButton = new QPushButton(tr("启动服务"));
    connect(startServiceButton, &QPushButton::clicked, this, &MainWindow::startService);
    
    stopServiceButton = new QPushButton(tr("停止服务"));
    connect(stopServiceButton, &QPushButton::clicked, this, &MainWindow::stopService);
    
    restartServiceButton = new QPushButton(tr("重启服务"));
    connect(restartServiceButton, &QPushButton::clicked, this, &MainWindow::restartService);
    
    buttonsLayout->addWidget(startServiceButton);
    buttonsLayout->addWidget(stopServiceButton);
    buttonsLayout->addWidget(restartServiceButton);
    
    mainLayout->addLayout(buttonsLayout);
}

void MainWindow::createStatusBar()
{
    statusLabel = new QLabel(tr("就绪"));
    serviceStatusLabel = new QLabel(tr("服务状态: 未知"));
    serviceStatusIcon = new QLabel();

    // 设置初始图标（未知状态，灰色点）
    QPixmap grayPixmap(16, 16);
    grayPixmap.fill(Qt::gray);
    serviceStatusIcon->setPixmap(grayPixmap);
    serviceStatusIcon->setToolTip(tr("服务状态未知"));

    statusBar()->addWidget(statusLabel, 1);
    statusBar()->addWidget(serviceStatusIcon);
    statusBar()->addWidget(serviceStatusLabel);
}

void MainWindow::createTrayIcon()
{
    if (!QSystemTrayIcon::isSystemTrayAvailable()) {
        return;
    }

    trayIconMenu = new QMenu(this);
    trayIconMenu->addAction(showMainAct);
    trayIconMenu->addAction(settingsAct);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(startAct);
    trayIconMenu->addAction(stopAct);
    trayIconMenu->addAction(restartAct);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(quitAct);

    trayIcon = new QSystemTrayIcon(this);
    trayIcon->setContextMenu(trayIconMenu);
    trayIcon->setIcon(QIcon(":/icons/application.png"));
    trayIcon->show();

    connect(trayIcon, &QSystemTrayIcon::activated,
            this, &MainWindow::trayIconActivated);
}

void MainWindow::updateServiceStatus()
{
    QProcess process;
    process.start("systemctl", QStringList() << "is-active" << "cpu-scheduler.service");
    process.waitForFinished();
    
    QString status = process.readAllStandardOutput().trimmed();
    if (status == "active") {
        trayIcon->setToolTip(tr("CPU调度优化工具\n服务状态: 运行中"));
        serviceStatusLabel->setText(tr("服务状态: 运行中"));
        // 设置运行中图标（绿色点）
        QPixmap greenPixmap(16, 16);
        greenPixmap.fill(Qt::green);
        serviceStatusIcon->setPixmap(greenPixmap);
        serviceStatusIcon->setToolTip(tr("服务正在运行"));
    } else if (status == "inactive") {
        trayIcon->setToolTip(tr("CPU调度优化工具\n服务状态: 已停止"));
        serviceStatusLabel->setText(tr("服务状态: 已停止"));
        // 设置停止状态图标（红色点）
        QPixmap redPixmap(16, 16);
        redPixmap.fill(Qt::red);
        serviceStatusIcon->setPixmap(redPixmap);
        serviceStatusIcon->setToolTip(tr("服务已停止"));
    } else {
        trayIcon->setToolTip(tr("CPU调度优化工具\n服务状态: 未知"));
        serviceStatusLabel->setText(tr("服务状态: 未知"));
        // 设置未知状态图标（灰色点）
        QPixmap grayPixmap(16, 16);
        grayPixmap.fill(Qt::gray);
        serviceStatusIcon->setPixmap(grayPixmap);
        serviceStatusIcon->setToolTip(tr("服务状态未知"));
    }
    
    statusLabel->setText(tr("最后更新: %1").arg(QTime::currentTime().toString("hh:mm:ss")));
}

void MainWindow::installService()
{
    // 使用构建目录下的脚本文件
    QString tempDir = QDir::currentPath();
    
    // 确保配置文件是最新的
    QStringList scriptFiles = {
        "cpu_scheduler.sh",
        "cpu-scheduler.service",
        "cpu-scheduler.conf",
        "install_service.sh",
        "uninstall_service.sh"
    };
    
    // 检查所有必需的文件是否存在
    for (const QString &fileName : scriptFiles) {
        QString filePath = tempDir + "/" + fileName;
        if (!QFile::exists(filePath)) {
            QMessageBox::warning(this, tr("错误"), 
                                tr("缺少必需的文件: %1\n请确保在构建目录中运行此程序").arg(fileName));
            return;
        }
    }
    
    // 使用pkexec或gksudo运行安装脚本
    QString command;
    QStringList args;
    
    // Try pkexec first (preferred method)
    if (QStandardPaths::findExecutable("pkexec") != QString()) {
        command = "pkexec";
        args << tempDir + "/install_service.sh";
    } 
    // Fallback to gksudo if pkexec is not available
    else if (QStandardPaths::findExecutable("gksudo") != QString()) {
        command = "gksudo";
        args << tempDir + "/install_service.sh";
    } 
    // Fallback to kdesudo if using KDE
    else if (QStandardPaths::findExecutable("kdesudo") != QString()) {
        command = "kdesudo";
        args << tempDir + "/install_service.sh";
    } 
    // If none of the GUI sudo tools are available, show an error
    else {
        QMessageBox::warning(this, tr("权限不足"), 
                             tr("未找到图形界面的权限提升工具 (如 pkexec, gksudo, kdesudo)。\n"
                                "请确保已安装这些工具之一，或在终端中手动运行安装脚本"));
        return;
    }
    
    QProcess *process = new QProcess(this);
    process->start(command, args);
    
    // Wait for the process to finish
    if (!process->waitForFinished(30000)) { // Wait up to 30 seconds
        QMessageBox::warning(this, tr("服务安装"), tr("操作超时"));
        process->kill();
        process->waitForFinished(1000);
    } else if (process->exitCode() == 0) {
        QMessageBox::information(this, tr("服务安装"), tr("服务安装成功"));
    } else {
        QString errorOutput = process->readAllStandardError();
        QMessageBox::warning(this, tr("服务安装"), 
                             tr("服务安装失败: %1").arg(errorOutput));
    }
    
    process->deleteLater();
    updateServiceStatus();
}

void MainWindow::uninstallService()
{
    int ret = QMessageBox::question(this, tr("确认卸载"), 
                                  tr("确定要卸载CPU调度服务吗？这将从系统中完全移除该服务。"),
                                  QMessageBox::Yes | QMessageBox::No);
    
    if (ret != QMessageBox::Yes) {
        return;
    }
    
    // 创建临时目录来存放脚本文件
    QString tempDir = QDir::tempPath() + "/cpu-scheduler";
    QDir dir(tempDir);
    if (!dir.exists()) {
        dir.mkpath(tempDir);
    }
    
    // 从资源中提取卸载脚本到临时目录
    QString resourcePath = ":/scripts/uninstall_service.sh";
    QString fileName = QFileInfo(resourcePath).fileName();
    QString tempPath = tempDir + "/" + fileName;
    
    QFile::remove(tempPath); // 删除已存在的文件
    if (!QFile::copy(resourcePath, tempPath)) {
        QMessageBox::warning(this, tr("错误"), 
                            tr("无法复制文件: %1 到 %2").arg(resourcePath).arg(tempPath));
        return;
    }
    
    // 设置执行权限
    QFile(tempPath).setPermissions(QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner |
                                  QFile::ReadGroup | QFile::ExeGroup |
                                  QFile::ReadOther | QFile::ExeOther);
    
    // Use pkexec or gksudo for GUI authentication
    QString command;
    QStringList args;
    
    // Try pkexec first (preferred method)
    if (QStandardPaths::findExecutable("pkexec") != QString()) {
        command = "pkexec";
        args << tempPath;
    } 
    // Fallback to gksudo if pkexec is not available
    else if (QStandardPaths::findExecutable("gksudo") != QString()) {
        command = "gksudo";
        args << tempPath;
    } 
    // Fallback to kdesudo if using KDE
    else if (QStandardPaths::findExecutable("kdesudo") != QString()) {
        command = "kdesudo";
        args << tempPath;
    } 
    // If none of the GUI sudo tools are available, show an error
    else {
        QMessageBox::warning(this, tr("权限不足"), 
                             tr("未找到图形界面的权限提升工具 (如 pkexec, gksudo, kdesudo)。\n"
                                "请确保已安装这些工具之一，或在终端中手动运行卸载脚本"));
        QFile::remove(tempPath);
        dir.rmdir(tempDir);
        return;
    }
    
    QProcess *process = new QProcess(this);
    process->start(command, args);
    
    // Wait for the process to finish
    if (!process->waitForFinished(30000)) { // Wait up to 30 seconds
        QMessageBox::warning(this, tr("服务卸载"), tr("操作超时"));
        process->kill();
        process->waitForFinished(1000);
    } else if (process->exitCode() == 0) {
        QMessageBox::information(this, tr("服务卸载"), tr("服务卸载成功"));
    } else {
        QString errorOutput = process->readAllStandardError();
        QMessageBox::warning(this, tr("服务卸载"), 
                             tr("服务卸载失败: %1").arg(errorOutput));
    }
    
    process->deleteLater();
    
    // 清理临时文件
    QFile::remove(tempPath);
    dir.rmdir(tempDir);
    
    updateServiceStatus();
}
